/**
 * Copyright 2009, by the authors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package com.google.code.docbkx.incubator.xmlconverter;

import com.google.code.xmltool.XMLDoc;
import com.google.code.xmltool.XMLDocument;

import java.io.*;


  /**
   * @goal from-csv
   */
public class CSVConverterMojo extends AbstractXMLConverterMojo
{
  /**
   * @parameter
   */
  private boolean headersOnFirstLine = false;
  /**
   * @parameter
   */
  private String separator = ",";

  public CSVConverterMojo()
  {
     super();
  }

  public boolean convert(File input, File output) throws IOException
  {
    if (input == null || output == null)
    {
      throw new IllegalArgumentException("Either input or output files must not be null");
    }
    if (!input.isFile())
    {
      throw new IllegalArgumentException("The input must be a file");
    }
    if(!output.exists())
    {
      if(!output.getParentFile().exists())
      {
        output.getParentFile().mkdirs();
      }
    }

    getLog().info("CSV conversion form %s to %s");
    final BufferedReader reader = new BufferedReader(new FileReader(input));
    XMLDocument doc = XMLDoc.newDocument().addRoot("csv");

    String line = null;

    while ((line = reader.readLine()) != null)
    {
      final String[] cols = line.split(separator);
      // headers
      if (headersOnFirstLine)
      {
        final XMLDocument headers = doc.addTag("header").addAttribute("count", "" + cols.length);
        // for each separated content
        for (String col : cols)
        {
          headers.addTag("column").addText(col);
        }
      }
      else
      {
        // content
        final XMLDocument rows = doc.addTag("row").addAttribute("count", "" + cols.length);
        for (String col : cols)
        {
          rows.addTag("column").addText(col);
        }
      }
    }


    // output to file
    doc.toStream(new FileWriter(output));


    return true;  //To change body of implemented methods use File | Settings | File Templates.
  }
}
